"use script";

const Sequelize = require("sequelize");

module.exports = (app) => {
  const { STRING, INTEGER, DATE } = Sequelize;
  const RoleModel = app.model.define(
    "role",
    {
      id: {
        type: INTEGER,
        primaryKey: true,
        autoIncrement: true,
        comment: "角色唯一标识符",
      },
      roleName: {
        field: "role_name",
        allowNull: false,
        type: STRING(100),
        comment: "角色名称，最大长度100个字符",
      },
      roleRoute: {
        field: "role_route",
        type: STRING(100),
        comment: "角色路由，最大长度100个字符",
      },
      isShow: {
        field: "is_show",
        type: INTEGER,
        defaultValue: 1,
        comment: "用户是否显示，1为显示，0为隐藏",
      },
      createdAt: {
        field: "created_at",
        type: DATE,
        comment: "创建时间",
      },
      updatedAt: {
        field: "updated_at",
        type: DATE,
        comment: "更新时间",
      },
    },
    {
      tableName: "role",
    }
  );

  // RoleModel.prototype.toJSON = function () {
  //   return {
  //     id: this.id,
  //     roleName: this.roleName,
  //     roleRoute: this.roleRoute,
  //   };
  // };

  RoleModel.associate = function () {
    RoleModel.hasMany(app.model.UsersModel, {
      foreignKey: "role_id",
      as: "users",
    });
    // RoleModel.belongsToMany(app.model.UsersModel, {
    //   through: "users_role",
    //   foreignKey: "role_id",
    //   otherKey: "user_id",
    //   as: "users",
    // });

    RoleModel.belongsToMany(app.model.MenuModel, {
      through: "role_menu",
      foreignKey: "role_id",
      otherKey: "menu_id",
      as: "menu",
    });
  };

  return RoleModel;
};
